package com.genesis.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.genesis.mall.common.Result;
import com.genesis.mall.entity.UmsResource;
import com.genesis.mall.entity.UmsResourceCategory;
import com.genesis.mall.service.IUmsResourceCategoryService;
import com.genesis.mall.service.IUmsResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 资源分类表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-08-01
 */
@Slf4j
@RestController
@RequestMapping("/resourceCategory")
public class UmsResourceCategoryController {
    @Autowired
    private IUmsResourceCategoryService resourceCategoryService;

    @Autowired
    private IUmsResourceService resourceService;

    /**
     * 资源分类
     *
     * @return
     */
    @GetMapping("/listAll")
    public Result<List<UmsResourceCategory>> listAll() {
        List<UmsResourceCategory> umsResourceCategories = resourceCategoryService.list();
        return Result.success(umsResourceCategories);
    }

    /**
     * 添加资源分类
     *
     * @param resourceCategory
     * @return
     */
    @PostMapping("/create")
    public Result<String> create(@RequestBody UmsResourceCategory resourceCategory) {
        resourceCategory.setCreateTime(LocalDateTime.now());
        resourceCategoryService.save(resourceCategory);
        return Result.success();
    }

    /**
     * 删除资源分类
     */
    @PostMapping("/delete/{id}")
    public Result<String> delete(@PathVariable Long id) {
        //根据id查询是否有绑定的资源
        LambdaQueryWrapper<UmsResource> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsResource::getCategoryId,id);
        List<UmsResource> resources = resourceService.list(lqw);
        if (!resources.isEmpty()){
            return Result.error("分类有绑定的资源,不能删除");
        }
        //删除分类
        resourceCategoryService.removeById(id);
        return Result.success();
    }

    /**
     * 修改分类信息
     */
    @PostMapping("/update/{id}")
    public Result<String> update(@PathVariable Long id,@RequestBody UmsResourceCategory resourceCategory){
        resourceCategoryService.updateById(resourceCategory);
        return Result.success();
    }


}
